﻿using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
using ZWFrameWork;

public class TexturePackerManager
{
    private static readonly Dictionary<string, Object[]> _atlasDic = new Dictionary<string, Object[]>(); //图集字典

    /// <summary>
    /// 加载图集
    /// </summary>
    public static void LoadAtlas(string atlasPath)
    {
        Debug.Log("加载图集{"+atlasPath+"}");
        if (!_atlasDic.ContainsKey(atlasPath))
        {
#if UNITY_EDITOR
        Object[] atlas = AssetDatabase.LoadAllAssetsAtPath(atlasPath);
#else
        Object[] atlas = AssetBundle.LoadFromFile(atlasPath).LoadAllAssets();
#endif
           _atlasDic.Add(atlasPath,atlas); 
        }
        else
        {
            Debug.Log("图集{0}已加载");
        }
    }


    /// <summary>
    /// 加载对应图集中，对应名称的精灵图片
    /// </summary>
    /// <param name="atlasPath">图集路径</param>
    /// <param name="spriteName">精灵名称</param>
    /// <returns>Sprite</returns>
    public static Sprite LoadSprite(string atlasPath, string spriteName)
    {
        Sprite sprite = ResourceManager.Instance.LoadSprite(atlasPath, spriteName);
        return sprite; //返回找到的 Sprite
    }


    /// <summary>
    /// 删除图集缓存
    /// </summary>
    /// <param name="atlasPath">图集路径</param>
    public static void DeleteAtlas(string atlasPath)
    {
        if (_atlasDic.ContainsKey(atlasPath)) _atlasDic.Remove(atlasPath);
    }

    /// <summary>
    /// 遍历图集并找出 Sprite
    /// </summary>
    /// <param name="atlas">Object[]</param>
    /// <param name="spriteName">精灵名称</param>
    /// <returns>Sprite</returns>
    private static Sprite SpriteFormAtlas(Object[] atlas, string spriteName)
    {
        foreach (var obj in atlas)
        {
            if (obj != null && obj is Sprite && obj.name == spriteName) return (Sprite)obj;
        }

        Debug.LogError("图集中未查找到名为<"+spriteName+">的精灵");
        return null;
    }
}